package org.lanyu.springainovel.common.controller;

import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.common.service.UserService;
import org.lanyu.springainovel.common.util.JwtTokenUtil;
import org.lanyu.springainovel.common.util.UserAuthUtil;
import org.lanyu.springainovel.common.vo.RestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制�? * 处理用户登录、注册等认证相关请求
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserAuthUtil userAuthUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public RestVO<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );
            
            // 设置认证信息到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取用户信息
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            
            User user = userService.getUserByUsername(userDetails.getUsername());
            
            // 生成包含用户ID的JWT令牌
            String jwt = jwtTokenUtil.generateTokenWithUserId(userDetails, user.getId(), user.getNickname());
            System.out.println("生成JWT令牌成功");
            
            // 准备响应
            Map<String, Object> response = new HashMap<>();
            response.put("token", jwt);
            response.put("userId", user.getId());
            response.put("username", user.getUsername());
            response.put("nickname", user.getNickname());
            response.put("role", user.getRole());
            
            System.out.println("=== AuthController.login 成功 ===");
            return RestVO.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return RestVO.fail("用户名或密码错误");
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public RestVO<?> register(@RequestBody User user) {
        try {
            boolean created = userService.createUser(user);
            if (created) {
                return RestVO.success("注册成功");
            } else {
                return RestVO.fail("注册失败");
            }
        } catch (RuntimeException e) {
            return RestVO.fail(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/me")
    public RestVO<?> getCurrentUser() {
        try {
            // 使用工具类获取当前用�?
            User user = userAuthUtil.getRequiredCurrentUser();
            
            // 移除敏感信息
            user.setPassword(null);
            
            return RestVO.success(user);
        } catch (RuntimeException e) {
            return RestVO.fail(e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public RestVO<?> logout() {
        // 清除安全上下�?
        SecurityContextHolder.clearContext();
        
        // 可以在这里添加额外的登出逻辑，如记录登出日志、清理会话等
        
        return RestVO.success("登出成功");
    }

    /**
     * 登录请求参数�?     */
    public static class LoginRequest {
        private String username;
        private String password;
        
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
    }
}
